﻿using System;
using System.Messaging;

namespace TSites.Utility
{
	public abstract class MSMQReceiver<T> : LoggerBase
	{
		protected string msmqQueuePath;
		protected MessageQueue _msmqQueue = null;
		
		public void InitializeMSMQ()
		{
			try
			{
				//If the Message queue does not exists at specified location create it
				if (MessageQueue.Exists(msmqQueuePath))
				{
					// creates an instance MessageQueue, which points 
					// to the already existing MyQueue
					_msmqQueue = new MessageQueue(msmqQueuePath);
				}
				else
				{
					// creates a new private queue
					_msmqQueue = MessageQueue.Create(msmqQueuePath);
				}
				_msmqQueue.Formatter = new BinaryMessageFormatter();
				_msmqQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(msmqQueue_ReceiveCompleted);
				_msmqQueue.BeginReceive();
			}
			catch (Exception ex)
			{
				Error(ex.Message, ex);
			}
		}

		/// <summary>
		/// Handles the ReceiveCompleted event of the msmq Queue request.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.Messaging.ReceiveCompletedEventArgs"/> instance containing the event data.</param>
		private void msmqQueue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
		{
			try
			{
				T Tobject = (T)e.Message.Body;
				HandleTobject(Tobject);
			}
			catch (Exception ex)
			{
				Error(ex.Message, ex);
			}
			_msmqQueue.BeginReceive();
		}

		protected abstract void HandleTobject(T Tobject);

		protected override Type LogPrefix
		{
			get { return typeof(T); }
		}
	}
}
